<!--
 * @Author: huangtianyang 916072572@qq.com
 * @Date: 2023-11-20 16:47:46
 * @LastEditors: huangtianyang
 * @LastEditTime: 2024-04-28 14:18:35
 * @FilePath: \cxl-driving-training\src\components\form\labelList.vue
-->
<template>
    <div class="tag-box">
        <div class="tag-item" v-for="(item, index) in list" :key="index">
            <div class="tag-sort" v-if="hasSort">标签{{ index + 1 }}：</div>
            <div class="tag-name">
                <el-input
                    v-model="item.label"
                    :disabled="disabled"
                    placeholder="请输入名称"
                    @blur="onBlur"
                    clearable
                ></el-input>
            </div>
            <div class="tag-describe">
                <el-input
                    v-model="item.describe"
                    :disabled="disabled"
                    placeholder="请输入描述"
                    clearable
                    @blur="onBlur"
                ></el-input>
            </div>
            <div class="tag-operate" v-if="!disabled">
                <!-- 只能填写N个标签 -->
                <el-button
                    icon="Plus"
                    type="primary"
                    v-if="index === list.length - 1 && index < count - 1"
                    @click="onClickAddTag"
                />
                <el-button icon="Delete" type="danger" v-if="list.length > 1" @click="onClickDeleteTag(index)" />
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { reactive, watchEffect } from 'vue'

const props = defineProps(['value', 'hasSort', 'count', 'disabled'])
const emits = defineEmits(['change'])

interface labelItem {
    label: string
    describe: string
}

const list: labelItem[] = reactive([])

watchEffect(() => {
    list.length = 0
    if (props.value.length === 0) {
        list.push({ label: '', describe: '' })
    } else {
        list.push(...(props.value as labelItem[]))
    }
})

//添加标签
const onClickAddTag = () => {
    list.push({ label: '', describe: '' })
    emits('change', list)
}
//删除标签
const onClickDeleteTag = (index: number) => {
    list.splice(index, 1)
    emits('change', list)
}
const onBlur = () => {
    emits('change', list)
}
</script>

<style scoped lang="scss">
.tag-box {
    .tag-item {
        display: flex;
        align-items: center;
        // margin-bottom: 16px;
        > div {
            margin-right: 16px;
        }

        &:not(:last-child) {
            margin-bottom: 16px;
        }
        .tag-sort {
            width: 60px;
        }
        .tag-name {
            width: 200px;
        }
        .tag-describe {
            width: 400px;
        }
        .tag-operate {
            width: 200px;
        }
    }
}
</style>
